﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;

namespace WebStore.Web.App.Utility.Helpers
{
    public static class HtmlExtensions
    {
        public static MvcHtmlString ValidatedEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
        {
            if (htmlHelper.ViewData.ModelMetadata.ModelType == null)
            {
                return new MvcHtmlString(String.Empty);
            }

            TagBuilder tagBuilder = new TagBuilder("input");
            var name = ExpressionHelper.GetExpressionText(expression);
            string validation = String.Empty;
            //Try to get the attributes for the property
            Object[] objects = typeof(TModel).GetProperty(name).GetCustomAttributes(true);
            foreach (Attribute attribute in objects)
            {
                if (attribute.GetType() == typeof(RequiredAttribute))
                {
                    validation += "validate[required]";
                }
                if (attribute.GetType() == typeof(RangeAttribute))
                {
                    var min = ((RangeAttribute)attribute).Minimum;
                    var max = ((RangeAttribute)attribute).Maximum;
                    validation += String.Format("validate[required, min[{0}],max[{1}]]", min, max);
                }
                if (attribute.GetType() == typeof(StringLengthAttribute))
                {
                    var minimumLength = ((StringLengthAttribute)attribute).MinimumLength;
                    var maximumLength = ((StringLengthAttribute)attribute).MaximumLength;
                    string validator = String.Format("maxSize[{0}]", maximumLength);

                    if (minimumLength >= 0)
                    {
                        validator += String.Format(",minSize[{0}]", minimumLength);
                    }
                    validation += String.Format("validate[required, {0}", validator);
                }
            }

            tagBuilder.GenerateId(name);
            tagBuilder.AddCssClass(validation);
            return new MvcHtmlString(tagBuilder.ToString());
        }
    }
}